# -*- coding: utf-8 -*-
import os 
import time 
 
from os.path import join, getsize 
from heapq import nlargest 
 
import requests
from bs4 import BeautifulSoup
import json
import urllib.request
import re #写正则表达式要导入的


def returnArr(url):
    questionString = ''
    answerString = ''
    realURL = ''
    if 'question' in url and 'answer' in url:
        arr = url.split('/')
        defIndex = len(arr) + 1
        for iString in arr:
            if defIndex == 1:
                questionString = iString.replace('\n', '');
                defIndex = len(arr) + 1
            if defIndex == 2:
                answerString = iString.replace('\n', '');
                defIndex = len(arr) + 1
            if iString == 'question':
                defIndex = 1;
            if iString == 'answer':
                defIndex = 2;
    
    if '-' in url and '知乎' in url:
        arrURL = url.split('https://www.zhihu.com')
        realURL = 'https://www.zhihu.com' + arrURL[len(arrURL) - 1]
    else:
        realURL = url 
    
    if questionString != '' and answerString != '' and realURL != '':
        print(questionString)
        print(answerString)
        netWork(realURL, questionString, answerString)



def netWork(url, questionString, answerString):
    headers = {
         "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "accept-language": "zh-CN,zh;q=0.9",
    "cache-control": "max-age=0",
    "priority": "u=0, i",
    "sec-ch-ua": "\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-dest": "document",
    "sec-fetch-mode": "navigate",
    "sec-fetch-site": "none",
    "sec-fetch-user": "?1",
    "upgrade-insecure-requests": "1",
    "cookie": "_zap=383d9fd2-c856-4386-b8a9-27a3f09224f2; d_c0=ANDcF2kCihiPTue158SS2AD5od1Y1OiB_30=|1714358515; __snaker__id=pgkfVM5KYQuZY08t; q_c1=c747c5728d7440b29e03167a792c26d8|1714358536000|1714358536000; _xsrf=SsWBG1lEAneiBkw6M9W1KPzR9CH0b2dh; __zse_ck=001_1jj44ZqT1HI/NGwTXAbTbOMO0S2/8I359Djq69bWG/1vwaXpo4Y6mswCDPStpBzLcRcJH6i=q2uVqO1b5Gz5K7cbITNTH7c02RNeZulpzQK43vVDS29CVwElWvBzSwsQ; z_c0=2|1:0|10:1725530275|4:z_c0|80:MS4xZ2psaEFBQUFBQUFtQUFBQVlBSlZUU08xdm1lc25mNEZxaUpuZENGS3U1U3RHRDVoOGQ0RG5nPT0=|3e5f727543375d537aebeeb8f44fca19ec890f0751f58c5aa948ec6b5d6ddf57; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1725410541,1725501268,1725601893,1725844093; HMACCOUNT=807DDABE7CE5B90A; SESSIONID=3Ks6ajdFG5ctPDC3rphxxc5uIwveAy268A7fioEfqeo; JOID=V18SAkwx_ZhC3OyBMTXdh20D_uArALbtcr-E5XF0yvswiqrAAk2xRiDc7ocxpK_09ykgkDZFws2z6CwU1ysdKj0=; osd=V1EXBU0x851F3eyPNDLch2MG-eErDrPqc7-K4HZ1yvU1javADEi2RyDS64AwpKHx8CggnjNCw8297SsV1yUYLTw=; BEC=9f6899d2c0337126a73fd6e01ed7c740; Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49=1725869144; tst=r"
    }
    print(url)
    response = requests.get(url,headers=headers)
    print('--------------------------------------->')
    print(response.text)
    try :
        if not '后自动跳转至回答所在的问题页' in response.text:
            # print(1111,response.text)
            beautifulSoup = BeautifulSoup(response.text, 'html.parser')
            
            # print(1112,)
            resultStrring = beautifulSoup.find('script', id = 'js-initialData')
            print(str(resultStrring))
            frame = str(resultStrring)
            newFrame = frame.replace('</script>', '')
            target = ">"
            index = newFrame.index(target)
            result = newFrame[index+1:]
            jsonModel = json.loads(result)
            print(jsonModel['initialState']['entities']['questions'])
                
            tmpTitle = jsonModel['initialState']['entities']['questions'][questionString]['title']
            tmpContent = jsonModel['initialState']['entities']['answers'][answerString]['content']
            # print(tmpTitle)
            print(tmpContent)
            if 'img' in tmpContent or 'IMG' in tmpContent:
                re_img = r'<[img|IMG].*?>' 
                re_img_rc = r'.+?data-original="(\S+)"' 
                img_url_list = []
                img_list= re.findall(re_img, tmpContent)#找到所有的img标签
                print(img_list)
                # if len(img_list) == 0:
                    
                for tag in img_list:
                    if '<i>' in tag:
                        continue;
                    if 'data-original' not in tag:
                        continue;
                    imgPath = re.findall(re_img_rc, tag)[0]
                    print(imgPath)
                    img_url_list.append(imgPath)#找到所有的img_url
                    
                arrPic = list(set(img_url_list))
                for item in arrPic:
                    downLoadPNG(item)
                    time.sleep(1);
                
                print('一共发现{}图片--------------------->'.format(len(arrPic)))
                # print()
        elif '后自动跳转至回答所在的问题页' in response.text:
            print('文章已经被删除-------------------->')  
        else:
            print('知乎被发现了-------------------->')  
    except Exception as e :
        print('报错了-------------------->{error}'.format(error=e)) 
    

def downLoadPNG(url):
    imgSavePath = 'trash3'
    print('url->{url}'.format(url=url))
    firstTag = url.split('?')[0].split('/')
    imgTypeArr = firstTag[len(firstTag) - 1].split('.')
    imgType = imgTypeArr[len(imgTypeArr) - 1]
    img_data = requests.get(url).content
    filepath = os.path.join(imgSavePath)
    fileName = "{a}/{b}.{c}".format(a=filepath, b=str(int(time.time())), c=imgType)
    if not os.path.exists(imgSavePath):
            os.makedirs(filepath)
    with open(fileName, 'wb') as f:
        f.write(img_data)

url = """
高中生可以穿光腿神器么? - 爱吃瓜的溪晨酱的回答 - 知乎
https://www.zhihu.com/question/643205947/answer/3419065792
"""

returnArr(url)





























# https://www.zhihu.com/people/87-69-33-1/pins
# https://www.zhihu.com/people/98-33-76-9/pins
# 有一个舞蹈学院毕业的女女是什么感觉？ - 爱做梦的小小的文章 - 知乎
# https://zhuanlan.zhihu.com/p/704008084



# 上海的你，择偶的标准是怎样的？ - 拾六的回答 - 知乎
# https://www.zhihu.com/question/308798869/answer/3180340505

# https://www.zhihu.com/people/bai-wa-mei-zu/answers


# https://www.zhihu.com/people/76-36-7-72-3/answers




















# 初三艺考生的软度展示 - 一只欧尼酱的文章 - 知乎
# https://zhuanlan.zhihu.com/p/666397153
# 请问这种腿算直吗？ - 萌之朱雀的回答 - 知乎
# https://www.zhihu.com/question/597046962/answer/3011672518
# 到底啥是玉足? - 安琪拉的回答 - 知乎 
# https://www.zhihu.com/question/620480225/answer/3213267513



# https://www.zhihu.com/question/417484887/answer/3155754841
# fetch("https://www.zhihu.com/commercial_api/banners_v3/answer_up?question_token=579244893&answer_token=3026215417", {
#   "headers": {
#     "sec-ch-ua": "\"Google Chrome\";v=\"113\", \"Chromium\";v=\"113\", \"Not-A.Brand\";v=\"24\"",
#     "sec-ch-ua-mobile": "?0",
#     "sec-ch-ua-platform": "\"Windows\""
#   },
#   "referrer": "https://www.zhihu.com/question/579244893/answer/3026215417?utm_id=0",
#   "referrerPolicy": "no-referrer-when-downgrade",
#   "body": null,
#   "method": "GET",
#   "mode": "cors",
#   "credentials": "omit"
# });


# https://www.zhihu.com/people/feng-huo-64-68/answers
# https://www.zhihu.com/people/oxemkc/answers
# https://www.zhihu.com/people/9-15-7-48-47/answers
# https://www.zhihu.com/people/85-50-27-82/answers

# https://www.zhihu.com/people/41-20-11-87-49/answers